package com.firstgroup.service.Impl;

import com.firstgroup.Utils.JwtUtil;
import com.firstgroup.Utils.ResponseResult;
import com.firstgroup.domain.Comment;
import com.firstgroup.domain.Interviewers;
import com.firstgroup.domain.OperationRecord;
import com.firstgroup.domain.User;
import com.firstgroup.repository.CommentRepository;
import com.firstgroup.repository.InterviewersRepository;
import com.firstgroup.repository.OperationRecordRepository;
import com.firstgroup.repository.UserRepository;
import com.firstgroup.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 创作人 王箫凯
 * Date 2021/8/9
 * Time 9:39
 *
 * @author 王箫凯
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserRepository userRepository;
    @Resource
    InterviewersRepository interviewersRepository;
    @Resource
    OperationRecordRepository operationRecordRepository;

    @Resource
    CommentRepository commentRepository;


    @Override
    public User findUser(String username) {
        User user = userRepository.findByUsername(username);

        return user;
    }

    @Override
    public ResponseResult login(String username, String password) {
        System.out.println(username);
        User user = userRepository.findUserByUsername(username);
        log.info("用户信息信息{}", user);
        if (user == null) {
            return ResponseResult.error("该用户不存在");
        }
        if (!user.getPassword().equals(password)) {
            return ResponseResult.error("账号或密码错误");
        }
        //到达此处为账号密码正确，那么生成token
        String token = JwtUtil.getToken(user);
        //返回token数据
        return ResponseResult.success("登陆成功", token);
    }

    @Override
    @Transactional
    public ResponseResult updateState(Integer studentId, String state) {
        Interviewers interviewers = interviewersRepository.findInterviewersByInterviewersId(studentId);
        if (interviewers == null) {
            return ResponseResult.error("该面试人员不存在");
        }
        Comment banUserByInterViewId = userRepository.findBanUserByInterViewId(interviewers.getInterviewersId());
        if ("黑名单".equals(interviewers.getState()) && banUserByInterViewId!=null){
            return ResponseResult.error("该人员已被拉黑，无法直接修改状态");
        }else if(banUserByInterViewId!=null){
            //表示其中一个表没有被修改
            int count = userRepository.updateState(studentId, "黑名单");
            return ResponseResult.error("该人员已被拉黑，无法直接修改状态");

        }
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm");

        interviewers.setUpdateStateTime(simpleDateFormat.format(date));
        /**
         * 操作记录保存
         */
        OperationRecord operationRecord=new OperationRecord();



        operationRecord.setStudentId(String.valueOf(studentId));
        operationRecord.setOperationTime(simpleDateFormat.format(date));
        operationRecordRepository.save(operationRecord);


        int count = userRepository.updateState(studentId, state);

        if (count > 0) {
            log.info("将学号为{}的同学由{}更改为：{}", studentId, interviewers.getStudentId(), state);
            return ResponseResult.success("在 "+simpleDateFormat.format(date)+" 将 "
                    +interviewers.getName()+" 的状态修改为 "+state);
        }
        return ResponseResult.error("更新失败");
    }


    /**
     * 查找所有的面试人员的信息
     *
     * @return 返回一个值 这个值表示这所有的数据
     */
    @Override
    public Interviewers findInterviewersByInterviewId(Integer studentId) {
        Interviewers student = interviewersRepository.findInterviewersByInterviewersId(studentId);
        return student;
    }

    @Override
    @Transactional
    public ResponseResult setPlaceAndTime(String place, String time, Integer[] interviewsIds) {
        int length= interviewsIds.length;
        int count=0;
        for (Integer studentId :
                interviewsIds) {
            count += interviewersRepository.setPlaceAndTime(place, time, studentId);
        }
        if (count == length) {
            return ResponseResult.success("修改成功");
        }
        return ResponseResult.error("修改失败");
    }


    @Override
    public User findById(int id) {
        User user = userRepository.findById(id);
        return user;
    }

    @Override
    public ResponseResult findByName(String name) {
        List<Interviewers> list = interviewersRepository.findInterByName(name);
        if (list.size() == 0) {
            return ResponseResult.error("没找到任何相关的信息");
        }
        return ResponseResult.success(list);
    }

    @Override
    public Integer updateUser(int id, String name, String username) {

        return userRepository.updateUser(id, name, username);
    }

    @Override
    public List<Object> findIdAndName() {
        return userRepository.findIdAndName();
    }

    @Override
    public ResponseResult FuzzyQuery(Integer choose, String like) {
        List<Interviewers> list;
        if (choose == 0 ){
            //根据姓名查询
             list= interviewersRepository.findByNameLike(like);
             if (list.size() == 0){
                 return ResponseResult.error("查询失败，没有找到任何结果");
             }
            log.info("查询结果:"+list);
             return ResponseResult.success(list);
        }
        if (choose == 1){
            //根据班级查询
            list=interviewersRepository.findInterviewersByClassesLike(like);
            if (list.size()==0){
                return ResponseResult.error("查询失败，没有找到任何结果");
            }
            log.info("查询结果:"+list);
            return ResponseResult.success(list);
        }
        return ResponseResult.error("未知错误!");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult batchChange(Integer[] ids, String state) {
        if (ids.length == 0 ){
            return ResponseResult.error("请选择需要被修改的人员");
        }
        int count =0;
        int bad =0 ;
        Interviewers interviewers;
        List<Integer> list=new ArrayList<>();
            for (Integer id : ids){
                //查询这个人是否存在
                interviewers=interviewersRepository.findInterviewersByInterviewersId(id);
                if (interviewers==null){
                    //表示这个人找不到 ，可以抛出异常，
                    log.info("找不到id为{}的面试人员" , id);
                    bad++;
                    list.add(id);
                }
                count+=userRepository.updateStateByInterviewId(id,state);
            }

        if (count!=ids.length){
            log.info("本应该处理{}条数据，实际处理{}条数据,{}未处理",ids.length,count,bad);
        }
        for (Integer badId : list){
            log.info("{}未处理",badId);
        }

        return ResponseResult.success("修改成功，将选中人员状态修改为"+state,ids);
    }

    @Override
    public ResponseResult findBanUsers() {
        List<Comment> findBanUsers=userRepository.findAllBanUser();
        return ResponseResult.success(findBanUsers);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult addBanUser(int userId,int interviewId,String content) {

        Interviewers interviewers = interviewersRepository.findByInterviewersId(interviewId);
        System.out.println(interviewers);
        if (interviewers == null) {
            return ResponseResult.error("不存在该面试人员");
        }
        Comment comments=userRepository.findBanUserByInterViewId(interviewers.getInterviewersId());
        if ( comments!=null && "黑名单".equals(interviewers.getState())){
            return ResponseResult.error("该用户已被拉入黑名单,无需操作");
        }else if (!"黑名单".equals(interviewers.getState()) && comments!=null){
            userRepository.updateState(interviewId,"黑名单");
            return ResponseResult.error("该用户已被拉入黑名单,无需操作");
        }
        User user = userRepository.findById(userId);
        Comment comment = new Comment();
        comment.setUsername(user.getUsername());
        comment.setUserid(userId);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime times = LocalDateTime.now();
        String time = df.format(times);
        if(content==null || content.replaceAll(" ","").length()==0){
            content="您放弃了您的资格";
        }
        comment.setContent("拉黑时间："+time +",拉黑原因：" + content);
        comment.setState("黑名单");
        comment.setInterviewrId(interviewId);
        comment.setInterviewrName(interviewers.getName());
        userRepository.updateState(interviewId,"黑名单");
        Comment res = commentRepository.save(comment);

        return ResponseResult.success(res);
    }

    @Override
    public ResponseResult findBanUserByInterviewId(Integer interviewId) {
        Comment comment =userRepository.findBanUserByInterViewId(interviewId);
        return ResponseResult.success(comment);
    }

}
